package com.gitee.wsl.collections.bean

import com.gitee.wsl.ext.array.contentEquals
import kotlin.jvm.Transient

/**
 * A `MultiKey` allows multiple map keys to be merged together.
 *
 *
 * The purpose of this class is to avoid the need to write code to handle
 * maps of maps. An example might be the need to look up a file name by
 * key and locale. The typical solution might be nested maps. This class
 * can be used instead by creating an instance passing in the key and locale.
 *
 *
 *
 * Example usage:
 *
 * <pre>
 * // populate map with data mapping key+locale to localizedText
 * Map map = new HashMap();
 * MultiKey multiKey = new MultiKey(key, locale);
 * map.put(multiKey, localizedText);
 *
 * // later retrieve the localized text
 * MultiKey multiKey = new MultiKey(key, locale);
 * String localizedText = (String) map.get(multiKey);
</pre> *
 *
 * @param <K> the type of keys
 * @since 3.0
</K> */
class MultiKey<K>(
    val keys: Array<out K>,
    makeClone: Boolean = true
)  {
    /** The individual keys  */
    //private val keys: Array<K?>

    /** The cached hashCode  */
    @Transient
    private var hashCode = 0

    /**
     * Constructor taking two keys.
     *
     *
     * The keys should be immutable.
     * If they are not then they must not be changed after adding to the MultiKey.
     *
     *
     * @param key1  the first key
     * @param key2  the second key
     */
    //constructor(vararg key: K) : this(key, false)

    /**
     * Constructor taking an array of keys, optionally choosing whether to clone.
     *
     *
     * **If the array is not cloned, then it must not be modified.**
     *
     *
     *
     * This method is public for performance reasons only, to avoid a clone.
     * The hash code is calculated once here in this method.
     * Therefore, changing the array passed in would not change the hash code but
     * would change the equals method, which is a bug.
     *
     *
     *
     * This is the only fully safe usage of this constructor, as the object array
     * is never made available in a variable:
     * <pre>
     * new MultiKey(new Object[] {...}, false);
    </pre> *
     *
     *
     * The keys should be immutable.
     * If they are not then they must not be changed after adding to the MultiKey.
     *
     *
     * @param keys  the array of keys, not null
     * @param makeClone  true to clone the array, false to assign it
     * @throws NullPointerException if the key array is null
     * @since 3.1
     */
    /**
     * Constructor taking an array of keys which is cloned.
     *
     *
     * The keys should be immutable.
     * If they are not then they must not be changed after adding to the MultiKey.
     *
     *
     *
     * This is equivalent to `new MultiKey(keys, true)`.
     *
     *
     * @param keys  the array of keys, not null
     * @throws NullPointerException if the key array is null
     */
    init {
        //this.keys = if (makeClone) keys.clone() else keys
        calculateHashCode(keys)
    }

    /**
     * Calculate the hash code of the instance using the provided keys.
     * @param keys the keys to calculate the hash code for
     */
    private fun calculateHashCode(keys: Array<out K>) {
        var total = 0
        for (key in keys) {
            if (key != null) {
                total = total xor key.hashCode()
            }
        }
        hashCode = total
    }

    /**
     * Compares this object to another.
     *
     *
     * To be equal, the other object must be a `MultiKey` with the
     * same number of keys which are also equal.
     *
     *
     * @param other  the other object to compare to
     * @return true if equal
     */
    override fun equals(other: Any?): Boolean {
        if (other === this) {
            return true
        }
        if (other is MultiKey<*>) {
            val otherMulti = other
            return keys.contentEquals(otherMulti.keys)
        }
        return false
    }

    /**
     * Gets the key at the specified index.
     *
     *
     * The key should be immutable.
     * If it is not then it must not be changed.
     *
     *
     * @param index  the index to retrieve
     * @return the key at the index
     * @throws IndexOutOfBoundsException if the index is invalid
     * @since 3.1
     */
    fun getKey(index: Int): K? {
        return keys[index]
    }

    /**
     * Gets a clone of the array of keys.
     *
     *
     * The keys should be immutable
     * If they are not then they must not be changed.
     *
     *
     * @return the individual keys
     */
//    fun getKeys(): Array<K> {
//        return keys.clone()
//    }

    /**
     * Gets the combined hash code that is computed from all the keys.
     *
     *
     * This value is computed once and then cached, so elements should not
     * change their hash codes once created (note that this is the same
     * constraint that would be used if the individual keys elements were
     * themselves [Map][java.util.Map] keys).
     *
     *
     * @return the hash code
     */
    override fun hashCode(): Int {
        return hashCode
    }

    /**
     * Recalculate the hash code after deserialization. The hash code of some
     * keys might have change (hash codes based on the system hash code are
     * only stable for the same process).
     * @return the instance with recalculated hash code
     */
    protected fun readResolve(): Any {
        calculateHashCode(keys)
        return this
    }

    /**
     * Gets the size of the list of keys.
     *
     * @return the size of the list of keys
     * @since 3.1
     */
    fun size(): Int {
        return keys.size
    }

    /**
     * Gets a debugging string version of the key.
     *
     * @return a debugging string
     */
    override fun toString(): String {
        return "MultiKey$keys"
    }

}

fun<K> MultiKey(vararg key: K) = MultiKey(key, false)